#!/bin/bash

if  [ ! -f /etc/profile.origin ]; then
    cp /etc/profile /etc/profile.origin
fi
#动态获取脚本执行路径
RUN_PATH=`cd $(dirname $0);pwd`
mkdir -p $RUN_PATH/temp
mkdir -p $RUN_PATH/audit
#给所有用户添加可写权限
chmod 777 .
chmod 777 $RUN_PATH/temp
chmod 777 $RUN_PATH/audit
sed -i '/dbAgentHookOracle.so/d' /etc/profile
sed -i '/dbAgentHookMysql.so/d' /etc/profile
sed -i '/dbAgentHookPGsql.so/d' /etc/profile
if [ "$LD_PRELOAD" = "" ];then
    #echo "LD_PRELOAD is null"
    echo "alias sqlplus='LD_PRELOAD=$RUN_PATH/dbAgentHookOracle.so sqlplus'" >> /etc/profile
    echo "alias mysql='LD_PRELOAD=$RUN_PATH/dbAgentHookMysql.so mysql'" >> /etc/profile
    echo "alias psql='LD_PRELOAD=$RUN_PATH/dbAgentHookPGsql.so psql'" >> /etc/profile
else
    #echo "before install LD_PRELOAD is $LD_PRELOAD"
    echo "alias sqlplus='LD_PRELOAD=$LD_PRELOAD:$RUN_PATH/dbAgentHookOracle.so sqlplus'" >> /etc/profile
    echo "alias sqlplus='LD_PRELOAD=$LD_PRELOAD:$RUN_PATH/dbAgentHookMysql.so mysql'" >> /etc/profile
    echo "alias sqlplus='LD_PRELOAD=$LD_PRELOAD:$RUN_PATH/dbAgentHookPGsql.so psql'" >> /etc/profile
fi
#source  /etc/profile
. /etc/profile
#对于使用su postgres的场景，登录的是non-login shell，/etc/profile不会生效，只会执行postgres用户主目录下的.bashrc
AllLoginUsers=`cat /etc/passwd | grep -v nologin | awk -F ':' '{print $1}' | xargs`
array=($AllLoginUsers)
for user in ${array[@]}
do
    user_home=`bash -c "cd ~$(printf %q $user) &> /dev/null && pwd"`
    echo "find login user $user, home is $user_home"
    #避免重复
    if [ "$user_home" != "" ];then
        if [ -f "$user_home/.bashrc" ];then
            sed -i '/dbAgentHookOracle.so/d' $user_home/.bashrc
            sed -i '/dbAgentHookMysql.so/d' $user_home/.bashrc
            sed -i '/dbAgentHookPGsql.so/d' $user_home/.bashrc
        fi
        #添加alias
        echo "alias sqlplus='LD_PRELOAD=/data/dbAuditAgent/dbagent2.29/dbAgentHookOracle.so sqlplus'" >> $user_home/.bashrc
        echo "alias mysql='LD_PRELOAD=/data/dbAuditAgent/dbagent2.29/dbAgentHookMysql.so mysql'" >> $user_home/.bashrc
        echo "alias psql='LD_PRELOAD=/data/dbAuditAgent/dbagent2.29/dbAgentHookPGsql.so psql'" >> $user_home/.bashrc
    fi
done
